package com.fhj.movie.activity;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.R.integer;
import android.content.Entity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.fhj.movie.adapter.FilmScheduleAdapter;
import com.fhj.movie.constant.FilmType;
import com.fhj.movie.entity.JyjCinemaDetailsEntity;
import com.fhj.movie.entity.JyjCinemaEntity;
import com.fhj.movie.entity.JyjCouponListEntity;
import com.fhj.movie.entity.JyjDetailListEntity;
import com.fhj.movie.entity.JyjMovieListEntity;
import com.fhj.movie.entity.JyjTicketUnitListEntity;
import com.fhj.movie.interfaces.CallbackInterface;
import com.fhj.movie_fhj_01.R;
import com.fhj.utils.HttpConnectionUtils;
import com.fhj.utils.JsonUtils;
import com.fhj.utils.ListOrder;
import com.jiayujie.httputils.CallBack;
import com.jiayujie.httputils.ImageDownLoad;

/**
 * 电影院详细信息表
 * @author jiayujie
 *
 */
public class JyjCinemaDetailsActivity extends FragmentActivity implements OnClickListener {
	
	private Map<Integer, Integer> serviceImg;
	
	private TextView title,name,grade,location;
	private CheckBox like;
	private RelativeLayout turndetails;
	private Button details;
	private LinearLayout aboutInfo;
	private HorizontalScrollView filmscroll;//水平存放影片图片的布局
	private LinearLayout films;
	private TextView filmname,filmscore;
	private Button  filmdetails;
	private ImageView newfilm;
	private LinearLayout datelayout;
	private ListView datelistview;
	private ProgressBar schduleBar;
	
	private Bitmap  bitmapCommon;
	
	private static int cityId ;
	private static int cinemaId ;
	private static int position;
	
	private boolean backgroundsign= true;
	
	public  Map<String, Integer> imageSign;//使用图片网址来存放影片类型
	
	private  int  filmtype = 0;//影片类型
	
	private JyjCinemaDetailsEntity entity;
	
	int imgindex =0;//scrollView中图片的位置
	
	private int movieIndex=0;//当前影院电影的序号
	
	
	private int filmsChildCount;//当前影院所有电影总数
	FrameLayout filmbackground;//影院电影布局背景
	ImageView  filmimage;//影院电影布局图片
	
	//时间表显示处理
	private  Handler scheduleHandler = new Handler(){
		public void handleMessage(Message msg) {
			schduleBar.setVisibility(View.GONE);
			datelistview.setVisibility(View.VISIBLE);
			showDateList((List<JyjTicketUnitListEntity>) msg.obj);
		};
	};
	
	
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.what==1) {
				if (msg.obj instanceof JyjCinemaDetailsEntity) {
					entity = (JyjCinemaDetailsEntity) msg.obj;
					
					addCinemaService(entity.getDetailLists());//影院提供服务类型加载
					scrollAddImageView(entity.getMovielist());//影院图片加载
					
					if (entity.getCouponList()!=null&&entity.getCouponList().size()>0) {
						details.setOnClickListener(JyjCinemaDetailsActivity.this);
					}
					//优惠信息添加点击事件
					
					turndetails.setOnClickListener(JyjCinemaDetailsActivity.this);
					
				}
			}
		}
		
		// TODO 影院提供服务类型加载
		private void addCinemaService(List<JyjDetailListEntity> detailLists) {
			if (detailLists!=null&&!detailLists.isEmpty()) {
				JyjDetailListEntity jyjDetailListEntity = null;
				for(int i=0;i<detailLists.size();i++){
					jyjDetailListEntity= detailLists.get(i);
					if (serviceImg.containsKey(jyjDetailListEntity.getType())) {
						ImageView imageView = new ImageView(JyjCinemaDetailsActivity.this);
						imageView.setImageResource(serviceImg.get(jyjDetailListEntity.getType()));
						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
								android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 
								android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
						imageView.setLayoutParams(params);
						aboutInfo.addView(imageView);
					}
				}
				aboutInfo.setVisibility(View.VISIBLE);
			}
		}

		//水平滚动条中添加图片
		private void scrollAddImageView(final List<JyjMovieListEntity> list) {
			
			imageSign = new HashMap<String, Integer>();
			
			if (list==null||list.size()==0) {
				return ;
			}
			
			//根据数据来加载默认的布局
			for(int i=0;i<list.size();i++){
				View  view = LayoutInflater.from(JyjCinemaDetailsActivity.this).inflate(R.layout.movie_detail_imagelayout, null);
				filmbackground = (FrameLayout) view.findViewById(R.id.movie_details_bg);
				RelativeLayout  overlay = (RelativeLayout)view.findViewById(R.id.movie_details_overlay);
				
				//设置第一个为选中的状态
				if (i==0) {
					filmbackground.setBackgroundResource(R.drawable.bg_movie);
					overlay.setVisibility(View.GONE);
				}
				films.addView(view,i);
				view.setOnClickListener(JyjCinemaDetailsActivity.this);
			}
			
			//获得视图中所有的元素的个数
			filmsChildCount = films.getChildCount();
			
			//开线程下载图片并且将图片填充到已经添加好的布局中
			final Handler downLoadHandler = new Handler(){
				public void handleMessage(Message msg) {
					
					View childView = films.getChildAt(msg.arg2);
					ImageView img = (ImageView)childView.findViewById(R.id.movie_details_movieimg);
					Bitmap bitmap = (Bitmap) msg.obj;
					img.setImageBitmap(bitmap);
					img.setPadding(8, 8, 8, 8);
					
					ImageView  sign = (ImageView)childView.findViewById(R.id.movie_details_sign);
					switch (msg.arg1) {
					case FilmType.D2_IMAX:
						sign.setImageResource(R.drawable.icon_type_2dimax);
						break;
					case FilmType.D3:
						sign.setImageResource(R.drawable.icon_type_3d);
						break;
					case FilmType.D3_IMAX:
						sign.setImageResource(R.drawable.icon_type_3dimax);
						break;
					default:
						sign.setVisibility(View.GONE);
						break;
					}
				};
			};
			
			for( imgindex = 0;imgindex<list.size();imgindex++){
				final JyjMovieListEntity downLoadImageEntity = list.get(imgindex);
				
				String filmType = downLoadImageEntity.getDimensional();
				if (filmType!=null) {
					if (filmType.equals("2D")) {
						filmtype=FilmType.D2;
					}else if (filmType.equals("2D,IMAX")) {
						filmtype = FilmType.D2_IMAX;
					}else if (filmType.equals("3D")) {
						filmtype = FilmType.D3;
					}else if (filmType.equals("3D,IMAX")) {
						filmtype = FilmType.D3_IMAX;
					}
				}
				imageSign.put(downLoadImageEntity.getLogo(), filmtype);
				
				
				ImageDownLoad.downLoadImage(downLoadImageEntity.getLogo(),  imgindex, new CallBack() {
					
					@Override
					public void returnResult(Bitmap bitmap, int index,String url) {
						// 图片的返回数据
						Message message = downLoadHandler.obtainMessage();
						message.arg1 =imageSign.get(url);
						message.arg2 = index;
						message.obj = bitmap;
						downLoadHandler.sendMessage(message);
						
					}
				});
				
				
//				showDateList(list);
				
			}
			showFilmDetails(list.get(0));//预加载第一页数据
			filmdetails.setOnClickListener(JyjCinemaDetailsActivity.this);//影片详情的点击事件
			
			//加载第一页时间表相关
			schduleBar.setVisibility(View.VISIBLE);
			HttpConnectionUtils.getFilmSchedule(JyjCinemaDetailsActivity.this, list.get(0).getId(), cinemaId, cityId, new CallbackInterface() {
				
				@Override
				public void JsonCallback(JSONObject object) {
					// TODO 自动生成的方法存根
					if (object!=null) {
						
						List<JyjTicketUnitListEntity> parseFilmSchedule = JsonUtils.parseFilmSchedule(object);
						Message msg = scheduleHandler.obtainMessage();
						msg.obj = parseFilmSchedule;
						scheduleHandler.sendMessage(msg);
						
					}
				}
			});
			imgindex = 0;
		}

	};

	
	//影院图片和下面的数据进行连接
	public void showFilmDetails(JyjMovieListEntity  movieListEntity) {
		filmname.setText(movieListEntity.getName());
		if (movieListEntity.getIsNew() == 1) {
			newfilm.setVisibility(View.VISIBLE);
		}
		filmscore.setText(movieListEntity.getGrade() + "分");
	}
	

	
	//展示下载的时间表列表
	public void  showDateList(final List<JyjTicketUnitListEntity> list){
		
		schduleBar.setVisibility(View.GONE);//progressBar消失
		
		datelayout.removeAllViews();//移除关联的日期数据
		
		 final FilmScheduleAdapter scheduleAdapter;
		 scheduleAdapter =new FilmScheduleAdapter();
		
		for(int i = 0;i<list.size();i++){
			JyjTicketUnitListEntity entity = list.get(i);
			
			if (entity.getIsHaveTicket()<0) {
				continue;
			}

			LinearLayout.LayoutParams params =new LinearLayout.LayoutParams(0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1);
			
			final TextView dateText = new TextView(JyjCinemaDetailsActivity.this);
			dateText.setLayoutParams(params);
			String ss = entity.getShowDate();
			String m = ss.substring(ss.length()-4, ss.length()-2);
			String d = ss.substring(ss.length()-2, ss.length());
			
			dateText.setText(m+"/"+d);
			dateText.setTextColor(Color.BLACK);
			dateText.setBackgroundResource(R.drawable.bg_date_unselect);
			dateText.setGravity(Gravity.CENTER);
			
			dateText.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO 点击更新对应影片的时间表
					dateText.setBackgroundResource(R.drawable.bg_date_select);
					int childCount = datelayout.getChildCount();
					for(int i=0;i<childCount;i++){
						TextView tv = (TextView) datelayout.getChildAt(i);
						if (tv!=dateText) {
							tv.setBackgroundResource(R.drawable.bg_date_unselect);
						}else {
							if (list.get(i).getTicketList().size()==0||list.get(i).getTicketList()==null) {
								Toast.makeText(JyjCinemaDetailsActivity.this, "当前没有售票信息", Toast.LENGTH_SHORT).show();
								return;
							}
							scheduleAdapter.init(JyjCinemaDetailsActivity.this,list.get(i).getTicketList());
							
							scheduleAdapter.notifyDataSetChanged();
							
							calculatorListHeight(scheduleAdapter);
						}
					}
					
				}
			});
			datelayout.addView(dateText);
		}
		View view = datelayout.getChildAt(0);
		view.setBackgroundResource(R.drawable.bg_date_select);
		scheduleAdapter.init(JyjCinemaDetailsActivity.this, list.get(0).getTicketList());
		datelistview.setAdapter(scheduleAdapter);
		calculatorListHeight(scheduleAdapter);
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_movie_details);
		position = getIntent().getIntExtra("position", 0);

		JyjCinemaEntity entity = ListOrder.list.get(position);
		
		cinemaId = entity.getId();//拿到影院Id
		cityId = getIntent().getIntExtra("cityId", 110000);//拿到城市Id
		
		findbyId();
		
		filmscroll.setSmoothScrollingEnabled(true);//设置scrollView平滑滑动
		
		title.setText(entity.getName());
		name.setText(entity.getName());
		grade.setText(String.valueOf(entity.getGrade())+"分");
		location.setText(entity.getAddress());
		
		serviceImg = new HashMap<Integer, Integer>();
		
		
		serviceImg.put(1, R.drawable.icon_service_visa);
		serviceImg.put(2, R.drawable.icon_service_glass);
		serviceImg.put(3, R.drawable.icon_service_imax);
		serviceImg.put(4, R.drawable.icon_service_imax);
		serviceImg.put(5, R.drawable.icon_service_park);
		serviceImg.put(6, R.drawable.icon_service_love);
		serviceImg.put(7, R.drawable.icon_service_child);
		serviceImg.put(8, R.drawable.icon_service_machine);
		serviceImg.put(9, R.drawable.icon_service_wifi);
		serviceImg.put(10, R.drawable.icon_service_coffee);
		
		
		//第一次请求获取影院详情界面的所有信息
		HttpConnectionUtils.getCinameDetailData(getApplicationContext(), cinemaId, cityId, new CallbackInterface() {
			
			@Override
			public void JsonCallback(JSONObject object) {
				JyjCinemaDetailsEntity parseCinemaDetails = JsonUtils.parseCinemaDetails(object);
				Message message = handler.obtainMessage(1);
				message.obj = parseCinemaDetails;
				handler.sendMessage(message);
			}
		});
		
	}
	
	/**
	 */
	private void findbyId() {
		title =  (TextView)this.findViewById(R.id.movie_details_title);
		name =  (TextView)this.findViewById(R.id.movie_details_name);
		grade =  (TextView)this.findViewById(R.id.movie_details_grade);
		location =  (TextView)this.findViewById(R.id.movie_details_location);
		like = (CheckBox)this.findViewById(R.id.movie_details_like);
		details = (Button)this.findViewById(R.id.movie_details_details);
		filmscroll = (HorizontalScrollView)this.findViewById(R.id.movie_details_filmscroll);
		films = (LinearLayout)this.findViewById(R.id.movie_details_films);
		filmname = (TextView)this.findViewById(R.id.movie_details_filmname);
		filmdetails = (Button)this.findViewById(R.id.movie_details_filmdetails);
		filmscore = (TextView)this.findViewById(R.id.movie_details_filmscore);
		newfilm = (ImageView)this.findViewById(R.id.movie_details_newfilm);
		datelayout = (LinearLayout)this.findViewById(R.id.movie_details_datelayout);
		datelistview = (ListView)this.findViewById(R.id.movie_details_datelistview);
		aboutInfo = (LinearLayout)this.findViewById(R.id.movie_details_aboutInfo);
		turndetails = (RelativeLayout)this.findViewById(R.id.movie_details_turndetails);
		schduleBar = (ProgressBar)this.findViewById(R.id.movie_details_progressBar);
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		
		//如果当前点击的view的父容器是ScrollView
		if (v.getParent()==films) {

			schduleBar.setVisibility(View.VISIBLE);//显示progressBar
			datelistview.setVisibility(View.GONE);
			
			
			for(int i = 0;i<filmsChildCount;i++){
				View  view = films.getChildAt(i);
				
				filmbackground = (FrameLayout) view.findViewById(R.id.movie_details_bg);
				RelativeLayout  overlay = (RelativeLayout)view.findViewById(R.id.movie_details_overlay);
				if (v ==view) {
					
					
					movieIndex= i;
					
					scrollViewSlip(view);
					 
					showFilmDetails(entity.getMovielist().get(i));//展示数据
					
					filmbackground.setBackgroundResource(R.drawable.bg_movie);
					overlay.setVisibility(View.GONE);
					
					HttpConnectionUtils.getFilmSchedule(JyjCinemaDetailsActivity.this, entity.getMovielist().get(i).getId(), cinemaId, cityId, new CallbackInterface() {
						
						@Override
						public void JsonCallback(JSONObject object) {
							// TODO 自动生成的方法存根
							if (object!=null) {
								List<JyjTicketUnitListEntity> parseFilmSchedule = JsonUtils.parseFilmSchedule(object);
								Message msg = scheduleHandler.obtainMessage();
								msg.obj = parseFilmSchedule;
								scheduleHandler.sendMessage(msg);
							}
						}
					});
					
					
				}else {
					filmbackground.setBackgroundColor(Color.TRANSPARENT);
					overlay.setVisibility(View.VISIBLE);
				}
			}
			
		}
		
		//影院详细地址信息跳转
		if (v.getId()==turndetails.getId()) {
			Intent  intent =  new Intent(JyjCinemaDetailsActivity.this, JyjCinemaDetailsDetailsActivity.class);
			intent.putExtra("position", position);
			startActivity(intent);
		}
		
		//影院提供优惠券显示实现
		if (v.getId()==details.getId()) {
			
			View  view  = LayoutInflater.from(this).inflate(R.layout.movie_details_piao_listview, null);
			
			LinearLayout linearLayout  = (LinearLayout) view.findViewById(R.id.movie_details_piao_mainlayout);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
			
			List<JyjCouponListEntity> couponList = entity.getCouponList();
			
			for(int i=0;i<couponList.size();i++){
				JyjCouponListEntity jyjCouponListEntity = couponList.get(i);
				View  v1 = LayoutInflater.from(JyjCinemaDetailsActivity.this).inflate(R.layout.movie_details_piao, null);
				TextView  name = (TextView)v1.findViewById(R.id.movie_details_piao_name);
				TextView  nowprice= (TextView)v1.findViewById(R.id.movie_details_piao_nowprice);
				TextView price = (TextView)v1.findViewById(R.id.movie_details_piao_price);
				TextView  content = (TextView)v1.findViewById(R.id.movie_details_piao_content);
				TextView  buy = (TextView)v1.findViewById(R.id.movie_details_piao_buy);
				
				name.setText(jyjCouponListEntity.getCouponName());
				
				nowprice.setText(""+jyjCouponListEntity.getPrice());
				
				price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
				price.setText(""+jyjCouponListEntity.getCouponListPrice());
				
				content.setText(jyjCouponListEntity.getCouponDesc());
				
				buy.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO 自动生成的方法存根
						startActivity(new Intent(JyjCinemaDetailsActivity.this, HyyLoginActivity.class));
					}
				});
				
				linearLayout.addView(v1);
			}
			
			PopupWindow  window  = new PopupWindow(
					view,
					android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 
					true
					);
			window.setAnimationStyle(R.style.popwindow_anim);
			window.setBackgroundDrawable(new BitmapDrawable());
			window.setOutsideTouchable(true);
			window.showAtLocation(v, Gravity.BOTTOM, 0, 0);
		}
		
		//影片详情界面的跳转
		if (v.getId()==filmdetails.getId()) {
			Intent  intent = new Intent(JyjCinemaDetailsActivity.this, FHFilmDetailActivity.class);
			intent.putExtra("movieId", entity.getMovielist().get(movieIndex).getId());
			startActivity(intent);
		}
	}
	
	
	public void scrollViewSlip(View  view ){
		
		int  x = (int) view.getX();
//		filmscroll.smoothScrollTo(0, 0);
//		int x = screenWidth/2;
		filmscroll.smoothScrollTo(x, 0);
	}
	public void calculatorListHeight(FilmScheduleAdapter  scheduleAdapter){
		//listview计算高度并且设置固定高度
		if (scheduleAdapter.getCount()!=0) {
			int height = 0;
			View  view = scheduleAdapter.getView(0, null, datelistview);
			view.measure(0, 0);
			for(int j=0;j<scheduleAdapter.getCount()+1;j++){
				height+= view.getMeasuredHeight();
			}
			ViewGroup.LayoutParams ps = datelistview.getLayoutParams();
			ps.height=height;
			datelistview.setLayoutParams(ps);
		}
	}
	
	//获取屏幕宽度高度等参数
	public void getScreenParamters(){
		DisplayMetrics  metrics =new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		int  screenWidth = metrics.widthPixels;//屏幕宽度像素值
		int  screenHeight = metrics.heightPixels;//屏幕高度像素值
		
		float  density = metrics.density;//获取屏幕密度（0.75 / 1.0 / 1.5）
		
		int  densityDpi = metrics.densityDpi;//屏幕密度DPI （120 / 160 / 240）
		
	}
	
}


